package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"melon/server/global"
	"net/http"
)

type VersionItem struct {
	Key   string `json:"key"`
	Val   string `json:"val"`
	Group string `json:"group"`
}

type VersionJson struct {
	Code   string        `json:"code"`
	Msg    string        `json:"msg,omitempty"`
	Result []VersionItem `json:"result,omitempty"`
}

func (w *VersionJson) VersionPage(c *gin.Context) {
	titles := []string{"下载地址", "版本号", "更新内容", "更新时间", "兼容版本"} // 原始slice

	client := &http.Client{}
	urlString := global.MelonYml.GetString("HttpClient.GetUrl")
	request, _ := http.NewRequest("GET", urlString, nil)
	request.Header.Set("Connection", "keep-alive")
	response, _ := client.Do(request)

	var resp []VersionItem
	if response.StatusCode == 200 {
		body, _ := ioutil.ReadAll(response.Body)

		var versionJson VersionJson
		err := json.Unmarshal(body, &versionJson)
		if err != nil {
			panic("解析失败")
		}

		resp = versionJson.Result
		for index, _ := range resp {
			resp[index].Group = titles[index]
		}
	}

	c.HTML(http.StatusOK, "main/version.html", gin.H{
		"objectBaseBean": resp,
	})
}
